<template>
    <div id="add-edit-model">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="100px" :rules="rules">
                <el-row :gutter="35">
                    <el-divider content-position="left">基础信息</el-divider>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="风险分区" prop="l_RiskPartitionId">
                            <el-select 
                                v-model="ruleForm.l_RiskPartitionId" 
                                filterable 
                                class="m-2" 
                                placeholder="选择风险分区" 
                                value-key="id"
                                popper-class="set-select"
                                :popper-append-to-body="false"
                            >
                                <el-option
                                    v-for="item in riskOptions"
                                    :key="item.id"
                                    :label="item.v_Name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="评价单位" prop="v_EvaluationUnit">
                            <el-input v-model="ruleForm.v_EvaluationUnit" placeholder="评价单位" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="评价日期" prop="d_EvaluationDate">
                            <el-date-picker
                                v-model="ruleForm.d_EvaluationDate"
                                type="date"
                                popper-class="el-date-p"
                                value-format="YYYY-MM-DD"
                                placeholder="请选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="评价单位资质">
                            <el-input v-model="ruleForm.v_UnitQualification" placeholder="评价单位资质" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="人员资质">
                            <el-input v-model="ruleForm.v_PenpleQualification" placeholder="人员资质" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="审核人">
                            <el-input v-model="ruleForm.v_Auditor" placeholder="审核人" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="批准人">
                            <el-input v-model="ruleForm.v_Approver" placeholder="批准人" clearable />
                        </el-form-item>
                    </el-col>
                    <el-divider content-position="left">评估报告文件上传</el-divider>
                    <div style="padding: 0 20px;width: 100%;">
                        <FileView
                            ref="fileRef"
                            isAccept=""
                            :isNeedRequest="true"
                            :fileInfo="fileInfo"
                            :componentKey="isAlter"
                        />
                    </div>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button type="primary" :loading="repeatDis" :disabled="repeatDis" @click="submitForm(ruleFormRef)">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue';
import FileView from '../file-view.vue';
import { 
    FormInstance, 
    FormRules, 
    ElButton, 
    ElCol, 
    ElDatePicker, 
    ElDialog, 
    ElForm, 
    ElFormItem, 
    ElInput, 
    ElOption, 
    ElRow, 
    ElSelect,
    ElMessage,
} from 'element-plus';
import { 
    SMSDCRiskPartitionList,
    SMSDCHazopAdd,
    SMSDCHazopUpdate,
} from '/@/api/centerControl/sms';
import { sysFileInfoYitId , sysFileInfoMultipleUpload } from '/@/api/centerControl/pubilc';
// 
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    l_RiskPartitionId: any, // 风险分区id
    v_EvaluationUnit: String, // 评价单位
    d_EvaluationDate: String, // 日期
    v_UnitQualification: String, // 评价单位资料
    v_PenpleQualification: String, // 人员资质
    v_Auditor: String, // 审核人
    v_Approver: String, // 批准人
    l_FileId: any, // 评估报告文件id
}
export default defineComponent( {
    name: 'add-edit-model',
    components: { FileView },
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref();
        const ruleFormRef = ref();
        const riskOptions = ref();
        const fileInfo = ref('');
        const fileRef:any = ref(null);
        let sourceId: any;

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 风险分区id
            l_RiskPartitionId: [
				{ required: true, message: '请选择风险分区', trigger: 'change' },
			],
            // 评价单位
            v_EvaluationUnit: [
				{ required: true, message: '请输入评价单位', trigger: 'blur' },
			],
            // 日期
            d_EvaluationDate: [
				{ required: true, message: '请选择日期', trigger: 'change' },
			],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    state.repeatDis = true;
                    let res: any;
                    let param = toRaw(state.ruleForm);
                    state.repeatDis = true;
                    try{
                        if(props.repairInfo !== ''){
                            res = await SMSDCHazopUpdate(param);
                        }else{
                            res = await SMSDCHazopAdd(param);
                        }
                        if(res.success) uploadFile();
                        else state.repeatDis = false;
                    }catch(error){ state.repeatDis = false; }
                }else{
                    console.log('error submit!');
					return false
                }
            })
        }

        /*** 上传图片 */
        const uploadFile = async() => {
            let rcs: any;
            if(fileRef.value && fileRef.value.fileList.length !== 0){
                let setArr:any = [];
                fileRef.value.fileList.map((i: any) => {setArr.push(i.raw)});
                let param: any = {};
                param.files = setArr;
                param.sourceId = sourceId;
                param.sourceType = 10;
                console.log(param,'param')
                rcs = await sysFileInfoMultipleUpload(param);
                try{
                    if(rcs.success){
                        ctx.emit('controlUseClick');
                        ctx.emit('updateData');
                        state.repeatDis = false;
                    }else{
                        state.repeatDis = false;
                        ctx.emit('controlUseClick');
                    }
                }catch(error){ state.repeatDis = false; }
            }else{
                ctx.emit('controlUseClick');
                ctx.emit('updateData');
                state.repeatDis = false;
            }
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /*** 获取风险分区数据 */
        const getInfoFun = async() => {
            let res: any = await SMSDCRiskPartitionList({});
            if(res.success) riskOptions.value = res.data;
        }

        /** 获取雪花id */
        const getXhFun = async() => {
            let res: any;
            res = await sysFileInfoYitId({});
            if(res.success){
                sourceId = res.data;
                fileInfo.value = JSON.stringify({sourceId: res.data});
                state.ruleForm.l_FileId = res.data;
            }
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                state.repeatDis = false;
                sourceId = 0;
                getInfoFun();
                if(props.repairInfo !== ''){
                    titleCon.value = '编辑';
                    state.ruleForm = JSON.parse(props.repairInfo);
                    fileInfo.value = JSON.stringify({sourceId: JSON.parse(props.repairInfo).l_FileId});
                    sourceId = JSON.parse(props.repairInfo).l_FileId;
                }else{
                    titleCon.value = '新增';
                    state.ruleForm = {
                        l_RiskPartitionId: '', // 风险分区id
                        v_EvaluationUnit: '', // 评价单位
                        d_EvaluationDate: '', // 日期
                        v_UnitQualification: '', // 评价单位资料
                        v_PenpleQualification: '', // 人员资质
                        v_Auditor: '', // 审核人
                        v_Approver: '', // 批准人
                        l_FileId: '', // 评估报告文件id
                    }
                    getXhFun();
                }
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            riskOptions,
            fileInfo,
            isAlter: 1,
            fileRef,
        }
    },
} )
</script>
<style scoped lang="scss">
#file-view{
    width: 100%;
}
:deep(.el-cascader){
    width: 100%;
}
:deep(.el-select){
    width: 100%!important;
}
:deep(.el-input){
    width: 100%;
}
</style>